package com.example;

// 测试目的：
// 确定当前线程因调用shareObject.wait(timeout)而进入休眠状态之后，如果超时时间到了，当前线程是会立即继续执行
// 还是会等抢到shareObject对象的监视器锁之后才会继续执行
// 测试结果：
// waiting的线程即使因超时时间到了而被唤醒，被唤醒后依旧要等到获取到shareObject的监视器锁之后才能继续运行下去
public class ThreadWaitingTest3 {

    public static class TestThread extends Thread{

        private final Object shareObject;

        public TestThread(Object shareObject){
            super("test");
            this.shareObject = shareObject;
        }

        @Override
        public void run() {

            synchronized (shareObject){
                try {
                    System.out.println("test线程即将进入waiting状态...");
                    long start = System.currentTimeMillis();
                    shareObject.wait(1000*20);
                    long end = System.currentTimeMillis();
                    System.out.println("测试线程休眠了" + (end-start)/1000 + "秒");
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {

        Object shareObject = new Object();
        TestThread thread = new TestThread(shareObject);
        thread.start();

        Thread.sleep(1000*5);
        synchronized (shareObject){
            System.out.println("主线程抢到了shareObject的监视器锁");
            System.out.println("主线程开始睡上30秒，以确保在此期间主线程一直占有shareObject的监视器锁");
            Thread.sleep(1000 * 30);
            System.out.println("现在test线程的超时时间肯定到了，test线程的状态为：" + thread.getState());
            System.out.println("主线程即将释放shareObject的监视器锁");
        }
    }
}
